let chatlast;
let ysjlist = [];
function xlhsc() {
    let timestamp = (Date.now().toString()).substring(8, 14);
    let randompart = (Math.random().toString(36).substring(7)).toUpperCase();
    let serial = timestamp + randompart;
    if (serial.length > 16) {
        return serial.substring(0, 16);
    } else {
        while (serial.length < 16) {
            randompart = (Math.random().toString(36).substring(7)).toUpperCase();
            serial += randompart.charAt(0);
        }
        return serial.substring(0, 16); 
    }
}

function wrapText(context, text, maxWidth, lineHeight, font) {
    let wrappedText = [];
    let line = '';

    for (let char of text) {
        let testLine = line + char;
        let metrics = context.measureText(testLine);
        let testWidth = metrics.width;
        if (testWidth > maxWidth && line.length > 0) {
            wrappedText.push(line);
            line = char;
        } else {
            line = testLine;
        }
    }

    if (line.length > 0) {
        wrappedText.push(line);
    }

    return wrappedText;
}
function createSeal(id,company,name){
    var canvas = document.getElementById(id);  
    var context = canvas.getContext('2d'); 
    var width=canvas.width/2;
    var height=canvas.height/2;
    context.lineWidth=7;
    context.strokeStyle="#f00";
    context.beginPath();
    context.arc(width,height,110,0,Math.PI*2);
    context.stroke();
    create5star(context,width,height,30,"#f00",0);  
    context.font = '22px Helvetica';
    context.textBaseline = 'middle';
    context.textAlign = 'center'; 
    context.lineWidth=1;
    context.fillStyle = '#f00';
    context.fillText(name,width,height+65);
    context.translate(width,height);
    context.font = '30px Helvetica'
    var count = company.length;
    var angle = 4*Math.PI/(3*(count - 1));
    var chars = company.split("");   
    var c;
    for (var i = 0; i < count; i++){
        c = chars[i];
        if(i==0)
            context.rotate(5*Math.PI/6);
        else
          context.rotate(angle);
        context.save(); 
        context.translate(90, 0);
        context.rotate(Math.PI/2);
        context.fillText(c,0, 5); 
        context.restore();             
    }
    function create5star(context,sx,sy,radius,color,rotato){
        context.save();  
        context.fillStyle=color;  
        context.translate(sx,sy);
        context.rotate(Math.PI+rotato);
        context.beginPath(); 
        var x = Math.sin(0);  
        var y= Math.cos(0);  
        var dig = Math.PI/5 *4;  
        for(var i = 0;i< 5;i++){
         var x = Math.sin(i*dig);  
         var y = Math.cos(i*dig);  
         context.lineTo(x*radius,y*radius);  
        }   
        context.closePath();  
        context.stroke();  
        context.fill();  
        context.restore();  
    }
}
function creatnewcanvasdemo() {
    var existingCanvas = document.getElementById('demo');
    if (existingCanvas) {
      existingCanvas.parentNode.removeChild(existingCanvas);
    }
    var canvas = document.createElement('canvas');
    canvas.id = 'demo';
    canvas.style.display = 'none';
    canvas.width = 650;
    canvas.height = 400;
    document.body.appendChild(canvas);
    return canvas;
  }
  function addwatermarks(canvas, watermarksCount, onepart, twopart, threepart) {
    var ctx = canvas.getContext('2d');
    var watermarkTexts = [onepart, twopart, threepart];
    var usedPositions = new Set(); 
    function isPositionAvailable(x, y, width, height) {
        var position = x + ',' + y;
        return !usedPositions.has(position) && 
               x + width < canvas.width && 
               y + height < canvas.height;
    }

    for (var i = 0; i < watermarksCount; i++) {
        var textIndex = Math.floor(Math.random() * watermarkTexts.length);
        var watermarkText = watermarkTexts[textIndex];
        var x, y, positionAvailable;

        do {
            x = Math.random() * (canvas.width - 100) + 50;
            y = Math.random() * (canvas.height - 30) + 30;
            var textWidth = ctx.measureText(watermarkText).width;
            var textHeight = 20; 
            positionAvailable = isPositionAvailable(x, y, textWidth, textHeight);
        } while (!positionAvailable);

        usedPositions.add(x + ',' + y);
        ctx.font = '20px Arial';
        ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
        ctx.fillText(watermarkText, x, y);
    }
}
function thebookicpsc() {
    chatlast = document.getElementById('form-forms').innerHTML;
    const domain = document.getElementById('domain').value;
    const owner = document.getElementById('owner').value;
    const ownerxz = document.getElementById('ownerxz').value;
    const date = document.getElementById('date').value;
    const certNumber = document.getElementById('certNumber').value;
    const websiteName = document.getElementById('websiteName').value;
    const serviceContent = document.getElementById('serviceContent').value;
    const canvas = document.getElementById('certificate');
    if(domain === '' || owner === '' || ownerxz === '' || date === '' || certNumber === '' || websiteName === '' || serviceContent === '') {
        alert('请键入完整信息');
        return false;
    }
    document.getElementById('buttontoshow').style.display = 'block';
    ysjlist['domain'] = domain;
    ysjlist['owner'] = owner;
    ysjlist['ownerxz'] = ownerxz;
    ysjlist['date'] = date;
    ysjlist['websiteName'] = websiteName;
    ysjlist['serviceContent'] = serviceContent;
    ysjlist['certNumber'] = certNumber;
    const ctx = canvas.getContext('2d');
    canvas.height = 600; 
    canvas.width = 650;
    const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
    gradient.addColorStop(0, '#efe8d1');
    gradient.addColorStop(0.5, '#fbfbf3');
    gradient.addColorStop(1, '#efe8d1');
    ctx.fillStyle = '#5969a6';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = gradient; 
    ctx.fillRect(10, 10, canvas.width - 20, canvas.height - 20);
    ctx.font = 'bold 34px Arial';
    ctx.fillStyle = '#000';
    ctx.textAlign = 'center';
    ctx.fillText('ICP备案证书', canvas.width / 2, 60);
    ctx.strokeStyle = "#000000";
    ctx.lineWidth = 2;
    ctx.beginPath();
    ctx.moveTo(10, 75); 
    ctx.lineTo(640, 75); 
    ctx.stroke();
    ctx.font = '28px Arial';
    ctx.textAlign = 'left';
    const contentX = 50;
    const contentY = 120;
    const lineHeight = 50;
    ctx.fillText('网站域名:', contentX, contentY);
    ctx.fillText(domain, contentX + 150, contentY);
    ctx.fillText('主办单位名称:', contentX, contentY + lineHeight);
    ctx.fillText(owner, contentX + 190, contentY + lineHeight);
    ctx.fillText('主办单位性质:', contentX, contentY+2 * lineHeight);
    ctx.fillText(ownerxz, contentX + 190, contentY +2* lineHeight);
    ctx.fillText('审核通过日期:', contentX, contentY + 3 * lineHeight);
    ctx.fillText(date, contentX + 190, contentY + 3 * lineHeight);
    ctx.fillText('ICP备案号:', contentX, contentY + 4 * lineHeight);
    ctx.fillText(certNumber, contentX + 150, contentY + 4 * lineHeight);
    ctx.fillText('网站名称:', contentX, contentY + 5 * lineHeight);
    ctx.fillText(websiteName, contentX + 150, contentY + 5 * lineHeight);
    ctx.fillText('网站内容:', contentX, contentY + 6 * lineHeight);
    const contentLines = wrapText(ctx, serviceContent, canvas.width - 230, lineHeight, '28px Arial');
    let currentY = contentY + 6 * lineHeight;
    contentLines.forEach(line => {
        ctx.fillText(line, contentX + 150, currentY);
        currentY += lineHeight;
    });
    const sealCanvas = creatnewcanvasdemo();
    createSeal('demo', certNumber, '备案证书');
    const sealX = canvas.width / 2;
    const sealY = canvas.height - 100;
    ctx.drawImage(sealCanvas, sealX - 80, sealY -180, 540, 340);
    ctx.lineWidth = 2;
    ctx.strokeStyle = '#000';
    ctx.strokeRect(10, 10, canvas.width - 20, canvas.height - 20);
    ctx.font = '15px Arial';
    ctx.fillStyle = '#000';
    ctx.fillText('发行日期：' + date, canvas.width - 180, canvas.height - 20);
    ctx.fillText('证书序列号：' + xlhsc(), 50, canvas.height - 20);
    addwatermarks(canvas,25,owner,certNumber,domain);
    document.getElementById('form-forms').innerHTML = canvas.innerHTML;
    document.getElementById('canvascsr').style.marginLeft = '360px';
    canvas.style.display = 'block';
}
document.getElementById('buttontoshow').onclick = function () {
    document.getElementById('form-forms').innerHTML = chatlast;
    document.getElementById('buttontoshow').style.display = 'none';
    document.getElementById('certificate').style.display = 'none';
    document.getElementById('domain').value = ysjlist['domain'];
    document.getElementById('owner').value = ysjlist['owner'];
    document.getElementById('ownerxz').value = ysjlist['ownerxz'];
    document.getElementById('date').value = ysjlist['date'];
    document.getElementById('certNumber').value = ysjlist['certNumber'];
    document.getElementById('websiteName').value = ysjlist['websiteName'];
    document.getElementById('serviceContent').value = ysjlist['serviceContent'];
};